﻿using System.Collections.Generic;
using System.Linq;
using Framework.Extensions;

namespace Framework.Sql
{
    public class DeleteSqlBuilder : SqlBuilderBase
    {
        public DeleteSqlBuilder(string connectionString, string tableName) : base(connectionString, tableName) { }

        public void ExecuteSql()
        {
            var sql = string.Format("delete from {0}{1}",
                TableName,
                Conditions.Any() ? (" where " + Conditions.SeparateBy(" and ")) : string.Empty);

            new SqlExecutor(ConnectionString).Exec(sql);
        }
    }

    public class DeleteXrefChildrenSqlBuilder : SqlBuilderBase
    {
        private readonly string _parentIdColumnName;
        private readonly int _id;
        private readonly string _idColumnName;
        private readonly IEnumerable<int> _idsToNotDelete;

        public DeleteXrefChildrenSqlBuilder(string connectionString, string tableName, string parentIdColumnName, int id, string idColumnName, IEnumerable<int> idsToNotDelete) : base(connectionString, tableName)
        {
            _parentIdColumnName = parentIdColumnName;
            _id = id;
            _idColumnName = idColumnName;
            _idsToNotDelete = idsToNotDelete;
        }

        public void ExecuteSql()
        {
            var sql = string.Format("delete from {0} where {1} = {2} and {3} not in ({4})",
                                    TableName,
                                    _parentIdColumnName,
                                    _id,
                                    _idColumnName,
                                    _idsToNotDelete.Select(i => i.ToString()).SeparateBy(", "));

            new SqlExecutor(ConnectionString).Exec(sql);
        }
    }
}